package services

import (
	"errors"
	"hft/Database/admin"
	"hft/global"
)

type AboutSmallCategory struct{}

func (*AboutSmallCategory) Create(data *admin.SmallCategory) (err error) {

	res := global.OC_DB.Where("id = ?", data.Name).FirstOrCreate(&data)

	if res.Error != nil {
		return errors.New("未知错误500")
	}

	if res.RowsAffected == 0 {
		return errors.New("该分类已存在")
	}

	return nil
}

func (*AboutSmallCategory) Edit(data *admin.SmallCategory) (err error) {

	err = global.OC_DB.Where("id = ?", data.ID).Model(&admin.SmallCategory{}).Updates(map[string]interface{}{
		"sort":      data.Sort,
		"name":      data.Name,
		"introduce": data.Introduce,
	}).Error

	if err != nil {
		return errors.New("未知错误500")
	}

	return nil
}

func (*AboutSmallCategory) List(category_id int) (list []*admin.SmallCategory, err error) {

	var smallCategoryList []*admin.SmallCategory

	global.OC_DB.Where("category = ?", category_id).Find(&smallCategoryList)

	return smallCategoryList, nil

}

func (*AboutSmallCategory) Delete(ids []int) (err error) {

	var list []*admin.SmallCategory

	global.OC_DB.Find(&list, ids)

	global.OC_DB.Unscoped().Delete(&list)

	return nil

}

var AboutSmallCategoryService = new(AboutSmallCategory)
